/*
 * BubbleView.java
 * classes : com.cc.bubbleanimation.BubbleView
 * @author Jun.w
 * V 1.0.0
 * Create at 2015年5月18日 下午2:16:58
 */
package com.cc.bubbleanimation;

import java.util.Random;

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

/**
 * com.cc.bubbleanimation.BubbleView
 * 
 * @author cc <br/>
 *         create at 2015年5月18日 下午2:16:58
 */
public class BubbleView extends View {

  private int x, y, radius;
  private Paint paint;
  private Context context;

  public BubbleView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
  }

  public BubbleView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
  }

  public BubbleView(Context context) {
    super(context);
    init(context);
  }

  private void init(Context context) {
    this.context = context;
    x = genRadius(getScreenWidth());
    Log.i("CC", "X是多少？：" + x);
    radius = genRadius();
    paint = new Paint();
    paint.setColor(Color.rgb(getRandom(255), getRandom(255), getRandom(255)));
    // setBackgroundColor(getResources().getColor(color.holo_green_dark));
  }

  @Override
  public void layout(int l, int t, int r, int b) {
    super.layout(x, 0, radius * 2 + x, radius * 2);
  }

  /*
   * (non-Javadoc)
   * 
   * @see android.view.View#onLayout(boolean, int, int, int, int)
   */
  @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
  }

  /**
   * 计算整个View的尺寸
   */
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(radius * 2, radius * 2);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG)); // 抗锯齿
    super.onDraw(canvas);
    canvas.drawCircle(radius, radius, radius, paint);
  }

  private int genRadius() {
    int min = 80, max = 300;
    Random random = new Random();
    return random.nextInt(max) % (max - min + 1) + min;
  }

  private int genRadius(int max) {
    return new Random().nextInt(max - radius);
  }

  private int getRandom(int max) {
    return new Random().nextInt(max);
  }

  public int getRadius() {
    return radius;
  }

  private int getScreenWidth() {
    DisplayMetrics metric = new DisplayMetrics();
    if (this.context instanceof Activity) {
      ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
    }
    return metric.widthPixels;
  }

}
